import { Filter, FilterResult } from './pool-filters';
import { LiquidityPoolKeysV4, Token, TokenAmount } from '@raydium-io/raydium-sdk';
import { Connection } from '@solana/web3.js';
import { logger, logPoolSize } from '../helpers';
import BN from 'bn.js';

export class PoolSizeFilter implements Filter {
  tokenHoldTimes = 65000;
  constructor(
    private readonly connection: Connection,
    private readonly quoteToken: Token,
    private readonly minPoolSize: TokenAmount,
    private readonly maxPoolSize: TokenAmount,
  ) {}

  async execute(poolKeys: LiquidityPoolKeysV4): Promise<FilterResult> {
    try {
      const response = await this.connection.getTokenAccountBalance(poolKeys.quoteVault, this.connection.commitment);
      const poolSize = new TokenAmount(this.quoteToken, response.value.amount, true);

      logger.info(
        {
          formatted: poolSize.toFixed(),
        },
        `池子大小检查`,
      );

      // 记录到本地文件
      logPoolSize({
        formatted: poolSize.toFixed(),
        mint: poolKeys.baseMint.toString(),
      });

      // 检查特殊情况：150 < 池子大小 < 150.1
      // const specialMin = new TokenAmount(this.quoteToken, '150', false);
      // const specialMax = new TokenAmount(this.quoteToken, '150.1', false);
      // if (poolSize.raw.gt(specialMin.raw) && poolSize.raw.lt(specialMax.raw)) {
      //   return {
      //     ok: false,
      //     message: `池子大小在特殊范围内: ${poolSize.toFixed()} (150-150.1) ${this.quoteToken.symbol}`,
      //   };
      // }

      // 计算代币的最大持有时间，150-270之间持有55s，大于270持有150s
      if ('150' < poolSize.toFixed() && poolSize.toFixed() < '270') {
        this.tokenHoldTimes = 65000;
      } else {
        this.tokenHoldTimes = 150000;
      }

      logger.info({ tokenHoldTimes: this.tokenHoldTimes }, `代币最大持有时间`);

      // 简化判断逻辑
      if (this.maxPoolSize && !this.maxPoolSize.isZero() && poolSize.raw.gt(this.maxPoolSize.raw)) {
        return {
          ok: false,
          message: `池子过大: ${poolSize.toFixed()} > ${this.maxPoolSize.toFixed()} ${this.quoteToken.symbol}`,
        };
      }

      if (this.minPoolSize && !this.minPoolSize.isZero() && poolSize.raw.lt(this.minPoolSize.raw)) {
        return {
          ok: false,
          message: `池子过小: ${poolSize.toFixed()} < ${this.minPoolSize.toFixed()} ${this.quoteToken.symbol}`,
        };
      }

      return { ok: true };
    } catch (error) {
      logger.error(
        {
          mint: poolKeys.baseMint.toString(),
          error: error instanceof Error ? error.message : '未知错误',
        },
        `检查池子大小失败`,
      );
      return { ok: false, message: '检查池子大小失败' };
    }
  }

  /**
   * 抛出代币的最大持有时间
   * @returns 最大持有时间（毫秒）
   */
  getTokenHoldTime(): number {
    return this.tokenHoldTimes;
  }
}
